package com.ctrip.ec.api.mobile.filter;

import com.ctrip.ec.api.mobile.common.RequestContext;
import com.ctrip.ec.api.mobile.controller.PaymentController;
import com.ctrip.ec.biz.dao.agent.AgentDao;
import com.ctrip.ec.biz.dao.member.MemberDao;
import com.ctrip.ec.biz.dao.user.UserDao;
import com.ctrip.ec.biz.entity.agent.AgentEntity;
import com.ctrip.ec.biz.entity.member.MemberEntity;
import com.ctrip.ec.biz.entity.member.MemberSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.sql.SQLException;
import java.sql.Timestamp;

/**
 * Created by jiangzy on 2018/5/2.
 */
public class AuthFilter implements Filter {


    private static MemberDao  member = new MemberDao();

    private  static AgentDao agent = new AgentDao();

    private final static Logger logger = LoggerFactory.getLogger(AuthFilter.class);


    public void init(FilterConfig filterConfig) throws ServletException {

    }


    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request =  (HttpServletRequest) servletRequest;
        String token =  request.getHeader("auth-token");
        String miniAppId = request.getHeader("miniAppId");
        if(token!= null && token.length()>0){
            try {

                MemberSession memberSession = member.entityByToken(token);
                if(memberSession != null) {
                   // logger.info("memberSession is not null :" + token);
                    memberSession.setLastVisit(new Timestamp(System.currentTimeMillis()));
                    RequestContext.setLoginMember(memberSession);
                }
                //RequestContext.setLoginToken(token);
            } catch (Exception e) {
                logger.error(e.getMessage(),e);
            }
        }
        if(miniAppId != null && miniAppId.length()>0){
            try {
                AgentEntity agentEntity = agent.entityByAppId(miniAppId);
                if(agentEntity != null){
                    RequestContext.setAgentId(agentEntity.getId());
                }
            } catch (SQLException e) {
                logger.error(e.getMessage(),e);
            }
        }
        filterChain.doFilter(servletRequest, servletResponse);

        RequestContext.clearLoginToken();
        RequestContext.clearResponseHeader();
        RequestContext.setAgentId(null);

    }

    public void destroy() {

    }
}
